/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-08-28
*/
package com.rzico.market.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ProductService;
import com.rzico.basics.service.SupplierService;
import com.rzico.core.service.SysEmployeeService;
import com.rzico.core.service.SysUserDataScopeService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.exception.CustomException;
import com.rzico.market.entity.Invoice;
import com.rzico.market.entity.InvoiceItem;
import com.rzico.market.service.InvoiceItemService;
import com.rzico.market.service.InvoiceService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;

import java.math.BigDecimal;
import java.util.*;

/**
 * 开票商品支付信息控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-08-28
 */
@Api(description = "开票商品支付信息接口")
@RestController
@RequestMapping("/admin/invoiceItem")
public class InvoiceItemController extends BaseController {

    @Autowired
    private InvoiceItemService invoiceItemService;

    @Autowired
    private EnterpriseService enterpriseService;


    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    protected SysEmployeeService sysEmployeeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserDataScopeService sysUserDataScopeService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private ProductService productService;

    /**
     * 分页查询开票商品支付信息
     *
     * @return
    */
    @ApiOperation("分页查询开票商品支付信息")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<InvoiceItem> list(Date startDate, Date endDate, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
           params.put("startDate", startDate);
        }
        if (endDate!=null){
           params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<InvoiceItem> list = invoiceItemService.selectList(params);
        PageResult<InvoiceItem> pageResult = new PageResult<InvoiceItem>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条开票商品支付信息
     *
     * @return
    */
    @ApiOperation("查询单条开票商品支付信息")
    @GetMapping("/find/{id}")
    public CommResult<InvoiceItem> find(@PathVariable String id) {
        InvoiceItem result = invoiceItemService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("invoiceItem",result);
        return CommResult.success(data);

    }

    /**
     * 保存开票商品支付信息
     *
     * @param invoiceItem
     * @return
     */
    @ApiOperation("保存开票商品支付信息")
    @PostMapping("/save")
    public CommResult<InvoiceItem> save(@RequestBody InvoiceItem invoiceItem) {
        int affectCount = invoiceItemService.insert(invoiceItem);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        InvoiceItem result = invoiceItemService.findById(invoiceItem.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除开票商品支付信息
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除开票商品支付信息", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除开票商品支付信息,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<InvoiceItem> del(@PathVariable String ids) {

        invoiceItemService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新开票商品支付信息
     *
     * @param invoiceItem
     * @return
     */
    @Log(desc = "更新开票商品支付信息", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新开票商品支付信息")
    @PostMapping("/update")
    public CommResult<InvoiceItem> update(@RequestBody InvoiceItem invoiceItem) {
        Enterprise enterprise = enterpriseService.getCurrent();
        if (null == enterprise) {
            return CommResult.error("没有开通企业");
        }
        Invoice invoice = invoiceService.findById(invoiceItem.getInvoiceId());
        InvoiceItem data = invoiceItemService.findById(invoiceItem.getId());
        if (0 < invoiceItem.getInvoiceAmount().compareTo(data.getAmount())) {
            throw new CustomException("商品开票支付金额大于付款金额，请修改");
        } else if (0 == invoiceItem.getInvoiceAmount().compareTo(data.getAmount())) {
            invoiceItem.setState(true);
        }else if (0 > invoiceItem.getInvoiceAmount().compareTo(data.getAmount())) {
            invoiceItem.setState(false);
        }
        //先求出发货单总金额，根据开票支付金额占总金额的比例计算出开票数量
        BigDecimal propNum = invoiceItem.getInvoiceAmount().divide(invoice.getSubPrice(), 2 , BigDecimal.ROUND_HALF_UP);
        invoiceItem.setOutInvoiceQuantity(propNum.multiply(invoice.getProductQuantity()));
        int affectCount = invoiceItemService.updateByPrimaryKeySelective(invoiceItem);
        if (affectCount <= 0){
            return CommResult.error();
        }
        InvoiceItem result = invoiceItemService.findById(invoiceItem.getId());
        return CommResult.success(result);
    }

}
